package com.dkd.flow.strategy;
import com.alibaba.fastjson2.JSONObject;
import com.dkd.flow.domain.EProcessInstances;
import com.dkd.flow.emums.FlowOperation;
import com.dkd.flow.strategy.annotation.Strategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
@Component
@Service
public class StrategyContext {
    // 线程安全
    private final Map<FlowOperation, CommonStrategy> strategyMap = new ConcurrentHashMap<>();
    @Autowired
    public StrategyContext(List<CommonStrategy> strategies) {
        this.strategyMap.clear();
        this.strategyMap.putAll(strategies.stream()
                .collect(Collectors.toMap(strategy -> AnnotationUtils.findAnnotation(strategy.getClass(),
                                        Strategy.class)
                                .value(),
                        strategy -> strategy)));
    }
    public Long execute(JSONObject data) {
        Integer operation = data.getInteger("operation");
        FlowOperation type = FlowOperation.getFlowOperationByValue(operation);
        if (type == null || !strategyMap.containsKey(type)) {
            throw new IllegalArgumentException("No strategy found for operation: " + operation);
        }
        return strategyMap.get(type)
                .execute(data);
    }
}